﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Comom.Project.ControllerCom;
using FarmeWork.Helper;
using dai_hoc_tuong_lai.Areas.Admin.Models;
using Dhtl.Service.IService;
using Comom.Project.JsonCom;
using DataBase.Daihoctuonglai;

namespace dai_hoc_tuong_lai.Areas.Admin.Controllers
{

    public class AdminController : UTController
    {

        private readonly IRoles _iRoles;
        private readonly IUser _iUser;
        private readonly IUserInRoles _iUserInRoles;
        private readonly EncryptPass mahoa = new EncryptPass();

        public AdminController(IRoles iRoles, IUser iUser, IUserInRoles iUserInRoles)
        {
            this._iRoles = iRoles;
            this._iUser = iUser;
            this._iUserInRoles = iUserInRoles;
        }


        //
        // GET: /Admin/Admin/
        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UpdateInfo()
        {
            UserModel model = new UserModel();
            var entity = _iUser.GetById(UtContext.User.Id);
            try
            {
                UserModel.MapFrom(entity, ref model);

                var gh = _iRoles.List();

                model.ModelCheck = new List<MoreInfoRoles>();

                if (gh.Count() > 0)
                {
                    foreach (var item in gh)
                    {
                        MoreInfoRoles itemCheck = new MoreInfoRoles()
                        {
                            Id = item.Id,
                            Name = item.Name,
                            Checkbox = _iUserInRoles.checkExitsRolesiD(entity.Id, item.Id),
                        };

                        model.ModelCheck.Add(itemCheck);
                    }
                }

                model.Pass = mahoa.Decrypt(model.Pass, "dailyphuthinh", true);

            }
            catch { }

            return PartialView("_UpdateInfo", model);
        }


        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddOrUpdate(UserModel model)
        {

            try
            {
                if (string.IsNullOrEmpty(model.Name))
                {
                    return JsonError("Nhập tên user vào");
                }

                if (string.IsNullOrEmpty(model.Email))
                {
                    return JsonError("Nhập email user vào");
                }

                if (!IsValidEmailAddress(model.Email))
                {
                    return JsonError("Nhập email user sai định dạng vào");
                }

                if (!string.IsNullOrEmpty(model.EmailNew))
                {
                    var c = _iUser.GetByEmail(model.EmailNew);
                    if (c != null)
                    {
                        return JsonError(" Email thay đổi đã tồn tại, vui lòng kiểm tra lại");
                    }

                    if (!IsValidEmailAddress(model.EmailNew))
                    {
                        return JsonError("Email thay đổi sai định dạng");
                    }

                    model.Email = model.EmailNew;
                }

                if (string.IsNullOrEmpty(model.Pass))
                {
                    return JsonError("Nhập password user vào");
                }

                if (!string.IsNullOrEmpty(model.PassNew))
                {
                    model.Pass = model.PassNew;
                }

                model.Pass = mahoa.Encrypt(model.Pass, "dailyphuthinh", true);

                var entity = new Usser();
                UserModel.MapFrom(model, ref entity);
                int idUs = _iUser.addOrupdate(entity);

                return JsonSuccess(null, "Cập nhật thông tin thành công");


            }
            catch (Exception ex)
            {
                return JsonError(ex.ToString());
            }
        }

        #region Images

        public string UploadImage(HttpPostedFileBase file)
        {
            string basePath = "~/Content/ImagesUpload";
            FileHelper fileHelper = new FileHelper(basePath);
            string fileName = fileHelper.SaveFile(null, file.FileName, file.InputStream);
            string filePathStr = Url.Content(basePath) + @"/" + fileName;
            return filePathStr;
        }

        [HttpPost]
        public ActionResult UploadImageStr(string qqfile)
        {
            string basePath = "~/Content/ImagesUpload";
            string[] fileNameArray = qqfile.Split(new char[] { '.' });
            if (fileNameArray.Length == 1)
            {
                return JsonError("lỗi");
            }
            FileHelper fileHelper = new FileHelper(basePath);
            string fileName = fileHelper.SaveFile(null, fileNameArray[1], Request.InputStream);
            string filePathStr = Url.Content(basePath) + @"/" + fileName;
            return Json(new { success = true, filePath = Url.Content(basePath) + @"/" + fileName });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum,
                                      string CKEditor, string langCode)
        {
            string url = string.Empty; // url to return
            string message = string.Empty; // message to display (optional)

            // here logic to upload image
            // and get file path of the image

            // path of the image
            string path = UploadImage(upload);

            // will create http://localhost:1457/Content/Images/my_uploaded_image.jpg

            url = Request.Url.GetLeftPart(UriPartial.Authority) + path;

            // passing message success/failure
            message = "Image was saved correctly";

            // since it is an ajax request it requires this string
            string output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\", \"" + message + "\");</script></body></html>";
            return Content(output);
        }

        #endregion
    }
}
